/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package sUtils;

import javax.microedition.lcdui.*;
import javax.microedition.io.Connector;
import javax.microedition.io.file.*;
import javax.microedition.media.*;
import javax.microedition.amms.*;
import javax.microedition.amms.control.*;
import javax.microedition.amms.control.camera.*;
import javax.microedition.media.control.VideoControl;



public class Images extends Canvas {

    public Canvas canvas() { return (Canvas)this; }

    static public int mergeKeyed( int keyColor, int c1, int c2, int c3, int c4 )
    {
        int col = (((((c1&0xff00)+(c2&0xff00)+(c3&0xff00)+(c4&0xff00))/4))&0xff00) +
        (((((c1&0xff00ff)+(c2&0xff00ff)+(c3&0xff00ff)+(c4&0xff00ff))/4))&0xff00ff);
        return col==keyColor ? col : (0xff000000+col);
    }

    static public int merge( int c1, int c2, int c3, int c4 )
    {
        int col = (((((c1&0xff00)+(c2&0xff00)+(c3&0xff00)+(c4&0xff00))/4))&0xff00) +
        (((((c1&0xff00ff)+(c2&0xff00ff)+(c3&0xff00ff)+(c4&0xff00ff))/4))&0xff00ff);
        return (0xff000000+col);
    }

    static public int combine( int col, int dest, double d )
    {
        int f = (int)(255.0*d);
        return  ((((col&0xff00ff)*(255-f) + (dest&0xff00ff)*f)>>8) & 0xff00ff) +
            ( (((col>>8)&0xff00ff)*(255-f) + ((dest>>8)&0xff00ff)*f) & 0xff00ff00 );
    }
    // load an filed image or by default a res image
    static public Image load( String file, String res )
    {
        Image ret = null;
        if (file!=null)
        {
            try {
                FileConnection f = (FileConnection) Connector.open(file,Connector.READ);
                ret = Image.createImage(f.openInputStream());
                f.close();
            } catch (Exception e) { ret = null; }
        }
        if (ret==null && res!=null)
        {
            try {
                ret = Image.createImage ( res );
            } catch (Exception e) { ret = null; }
        }
        return ret;
    }

    static public Image setOpacity( Image img, double d )
    {
        if (img!=null)
        {
            int f = ((int)(255.0*d)<<24)|0xffffff;
            int w = img.getWidth();
            int h = img.getHeight();
            int [] rgb = new int[w*h];
            img.getRGB(rgb, 0, w, 0, 0, w, h);
            for ( int i=0; i<w*h; i++ ) rgb[i] &= f;
            return Image.createRGBImage(rgb, w, h, true);
        }
        return null;
    }


    static public Image scaleDown( Image src )
    {
        if (src==null) return null;
        int sw = src.getWidth();
        int sh = src.getHeight();
        int dw = sw/2;
        int dh = sh/2;

        int srcRGB[] = new int[sw*sh];
        int dstRGB[] = new int[dw*dh];
        src.getRGB(srcRGB, 0, sw, 0, 0, sw, sh);

        for ( int y=0; y<dh; y++ ) for ( int x=0, ofs=y*2*sw; x<dw; x++, ofs+=2 )
               dstRGB[x+y*dw] = merge( srcRGB[ofs], srcRGB[ofs+1], srcRGB[ofs+sw], srcRGB[ofs+sw+1]);

        return Image.createRGBImage(dstRGB, dw, dh, false);
    }

    static public Image scaleDownKeyed( Image src, int keyColor )
    {
        if (src==null) return null;
        int sw = src.getWidth();
        int sh = src.getHeight();
        int dw = sw/2;
        int dh = sh/2;

        int srcRGB[] = new int[sw*sh];
        int dstRGB[] = new int[dw*dh];
        src.getRGB(srcRGB, 0, sw, 0, 0, sw, sh);

        for ( int y=0; y<dh; y++ ) for ( int x=0, ofs=y*2*sw; x<dw; x++, ofs+=2 )
               dstRGB[x+y*dw] = mergeKeyed( keyColor, srcRGB[ofs], srcRGB[ofs+1], srcRGB[ofs+sw], srcRGB[ofs+sw+1]);

        return Image.createRGBImage(dstRGB, dw, dh, true);
    }

    static public byte[] cameraSnapshotRaw( int w, int h, boolean show )
    {
        VideoControl videoControl=null;
        FlashControl flashControl=null;
        Player player=null;
        try {
            player = Manager.createPlayer("capture://video");

            player.realize();
            flashControl = (FlashControl)player.getControl("FlashControl");
            videoControl = (VideoControl)player.getControl("VideoControl");
            videoControl.initDisplayMode(VideoControl.USE_GUI_PRIMITIVE, null);
                videoControl.setDisplayLocation(0, 0);
                videoControl.setDisplaySize(w, h);
            videoControl.setVisible(show);
            player.start();
            flashControl.setMode(FlashControl.OFF);
            byte[] raw = videoControl.getSnapshot("image/jpeg");
            player.deallocate();
            player.close();
            return raw;

        } catch (Exception e) {} finally { if (player!=null) player.close(); }
        return null;
    }

    public void paint(Graphics g)
    {
    }

    static public boolean save( Image img, String name )
    {
        if (name==null || img==null) return false;
        String ext = name.toLowerCase(), mime = "image/jpeg";
        if (ext.endsWith(".png")) mime = "image/png"; else
        if (ext.endsWith(".gif")) mime = "image/gif"; else
        if (ext.endsWith(".tif")) mime = "image/tiff"; else
        if (ext.endsWith(".raw")) mime = null;
        if (!name.startsWith("file://")) name = "file://"+name;
        boolean ret = false;
        try
        {
            FileConnection f = (FileConnection) Connector.open(name);
            if (f.exists()) f.delete(); f.create();
            
            if (mime==null)
            {
                int w = img.getWidth(), h = img.getHeight();
                int [] rgb = new int[w*h];
                byte [] data = new byte [w*h*3];
                img.getRGB(rgb,0,w,0,0,w,h);
                for ( int i=0,o=0; i<w*h; i++,o+=3 )
                {
                    data[o] = (byte)((rgb[i]>>16)&0xff);
                    data[o+1] = (byte)((rgb[i]>>8)&0xff);
                    data[o+2] = (byte)((rgb[i])&0xff);
                }
                f.openOutputStream().write( data,0,w*h*3);
            }
            else
            {
                MediaProcessor mp = GlobalManager.createMediaProcessor("image/raw");
                mp.setOutput(f.openOutputStream());
                mp.setInput(img);
                ImageFormatControl fc = (ImageFormatControl)mp.getControl("javax.microedition.amms.control.ImageFormatControl");
                if (fc!=null) fc.setFormat(mime);
                mp.start();
                mp.complete();
            }
            ret=true;
        } catch( Exception e )
        {
            ret=false;
        }
        return ret;
    }

    static public Image graphicsImage( Canvas c )
    {
        int w = c.getWidth();
        int h = c.getHeight();
        Image img = Image.createImage( w,h );
        Graphics g = img.getGraphics();
        g.setClip(0,0,w,h);
        g.setColor(0);
        g.fillRect(0,0,w,h);
        return img;
    }

    public boolean screenshot( String name )
    {
        final String n = name;
        final int w = getWidth();
        final int h = getHeight();
        new Thread ( new Runnable() { public void run () {
        try {
            Image img = Image.createImage( w,h );
            Graphics g = img.getGraphics();
            g.setClip(0,0,w,h);
            g.setColor(0);
            g.fillRect(0,0,w,h);
            paint( g );
            Images.save( img,n );
        } catch (Exception exc) { }
        }}).start ();
        return true;
    }
}
